package cn.gcyl.module.biz.controller.app;

import cn.gcyl.framework.apilog.core.annotation.ApiAccessLog;
import cn.gcyl.framework.common.pojo.CommonResult;
import cn.gcyl.framework.common.pojo.PageParam;
import cn.gcyl.framework.common.pojo.PageResult;
import cn.gcyl.framework.common.util.object.BeanUtils;
import cn.gcyl.framework.excel.core.util.ExcelUtils;
import cn.gcyl.module.biz.controller.admin.alliancemembers.vo.AllianceMembersPageReqVO;
import cn.gcyl.module.biz.controller.admin.alliancemembers.vo.AllianceMembersRespVO;
import cn.gcyl.module.biz.controller.admin.alliancemembers.vo.AllianceMembersSaveReqVO;
import cn.gcyl.module.biz.controller.admin.carouselimage.vo.CarouselImagePageReqVO;
import cn.gcyl.module.biz.controller.admin.carouselimage.vo.CarouselImageRespVO;
import cn.gcyl.module.biz.controller.admin.columntype.vo.ColumnTypePageReqVO;
import cn.gcyl.module.biz.controller.admin.columntype.vo.ColumnTypeRespVO;
import cn.gcyl.module.biz.controller.admin.marketinformation.vo.MarketInformationPageReqVO;
import cn.gcyl.module.biz.controller.admin.marketinformation.vo.MarketInformationRespVO;
import cn.gcyl.module.biz.controller.admin.platforminformation.vo.AppPlatformInformationPageReqVO;
import cn.gcyl.module.biz.controller.admin.platforminformation.vo.PlatformInformationPageReqVO;
import cn.gcyl.module.biz.controller.admin.platforminformation.vo.PlatformInformationRespVO;
import cn.gcyl.module.biz.controller.admin.specialmeeting.vo.AppSpecialMeetingPageReqVO;
import cn.gcyl.module.biz.controller.admin.specialmeeting.vo.SpecialMeetingPageReqVO;
import cn.gcyl.module.biz.controller.admin.specialmeeting.vo.SpecialMeetingRespVO;
import cn.gcyl.module.biz.controller.admin.thirdpartyinformation.vo.AppThirdPartyInformationPageReqVO;
import cn.gcyl.module.biz.controller.admin.thirdpartyinformation.vo.ThirdPartyInformationRespVO;
import cn.gcyl.module.biz.dal.dataobject.alliancemembers.AllianceMembersDO;
import cn.gcyl.module.biz.dal.dataobject.carouselimage.CarouselImageDO;
import cn.gcyl.module.biz.dal.dataobject.columntype.ColumnTypeDO;
import cn.gcyl.module.biz.dal.dataobject.conferenceregistrationinformation.ConferenceRegistrationInformationDO;
import cn.gcyl.module.biz.dal.dataobject.marketinformation.MarketInformationDO;
import cn.gcyl.module.biz.dal.dataobject.platforminformation.PlatformInformationDO;
import cn.gcyl.module.biz.dal.dataobject.specialmeeting.SpecialMeetingDO;
import cn.gcyl.module.biz.dal.dataobject.thirdpartyinformation.ThirdPartyInformationDO;
import cn.gcyl.module.biz.dal.dataobject.useractionlog.UserActionLogDO;
import cn.gcyl.module.biz.dal.dataobject.usercolumnviewlog.UserColumnViewLogDO;
import cn.gcyl.module.biz.dal.mysql.conferenceregistrationinformation.ConferenceRegistrationInformationMapper;
import cn.gcyl.module.biz.dal.mysql.useractionlog.UserActionLogMapper;
import cn.gcyl.module.biz.service.alliancemembers.AllianceMembersService;
import cn.gcyl.module.biz.service.carouselimage.CarouselImageService;
import cn.gcyl.module.biz.service.columntype.ColumnTypeService;
import cn.gcyl.module.biz.service.marketinformation.MarketInformationService;
import cn.gcyl.module.biz.service.platforminformation.PlatformInformationService;
import cn.gcyl.module.biz.service.specialmeeting.SpecialMeetingService;
import cn.gcyl.module.biz.service.thirdpartyinformation.ThirdPartyInformationService;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import static cn.gcyl.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.gcyl.framework.common.pojo.CommonResult.success;
import static cn.gcyl.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "app - 首页接口")
@RestController
@RequestMapping("/app/members-home")
@Validated
public class AppMemberHomePageController {

    @Resource
    private AllianceMembersService allianceMembersService;
    @Resource
    private PlatformInformationService platformInformationService;
    @Resource
    private SpecialMeetingService specialMeetingService;
    @Resource
    private ThirdPartyInformationService thirdPartyInformationService;
    @Resource
    private MarketInformationService marketInformationService;
    @Resource
    private UserActionLogMapper userActionLogMapper;
    @Resource
    private CarouselImageService carouselImageService;
    @Resource
    private ColumnTypeService columnTypeService;
    @Resource
    private ConferenceRegistrationInformationMapper conferenceRegistrationInformationMapper;
//    @GetMapping("/getAppAllianceMembers")
//    @Operation(summary = "获得app联盟成员链接")
//    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    public CommonResult<AllianceMembersRespVO> getAppAllianceMembers(@RequestParam("id") Integer id) {
//        AllianceMembersDO allianceMembers = allianceMembersService.getAppAllianceMembers(id);
//        return success(BeanUtils.toBean(allianceMembers, AllianceMembersRespVO.class));
//    }

    @PostMapping("/getAllianceMembersPage")
    @Operation(summary = "获得app联盟成员链接分页")
    public CommonResult<PageResult<AllianceMembersRespVO>> getAllianceMembersPage(@Valid @RequestBody AllianceMembersPageReqVO pageReqVO) {
        PageResult<AllianceMembersDO> pageResult = allianceMembersService.getAllianceMembersPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, AllianceMembersRespVO.class));
    }
    @GetMapping("/getAppAllianceMembersInfoPage")
    @Operation(summary = "获得app联盟成员链接信息列表")
    public CommonResult<PageResult<PlatformInformationDO>> getAppAllianceMembersInfoPage(@Valid AppPlatformInformationPageReqVO pageReqVO) {
        PageResult<PlatformInformationDO> pageResult = allianceMembersService.getAppAllianceMembersInfoPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, PlatformInformationDO.class));
    }

    @GetMapping("/getAppPlatformInformation")
    @Operation(summary = "获得app平台信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PermitAll
    public CommonResult<PlatformInformationRespVO> getAppPlatformInformation(@RequestParam("id") Long id) {
        Long loginUserId = getLoginUserId();
        PlatformInformationDO platformInformation = platformInformationService.getAppPlatformInformation(id);
        PlatformInformationRespVO bean = BeanUtils.toBean(platformInformation, PlatformInformationRespVO.class);
        String userCollectIds = platformInformation.getUserCollectIds();
        // 使用Stream的检查方式
        boolean isCollected = false;
        if (userCollectIds != null && !userCollectIds.isEmpty()) {
            isCollected = Arrays.stream(userCollectIds.split(","))
                    .map(String::trim)
                    .anyMatch(ids -> ids.equals(loginUserId.toString()));
        }
        bean.setIsCollect(isCollected ? 1 : 0);

        if (ObjectUtil.isNotEmpty(loginUserId)){
        String registeredUserIds = bean.getRegisteredUserIds();
        String consultingUserIds = bean.getConsultingUserIds();
            String isSignUpIds = bean.getIsSignUpIds();
            // 判断用户是否已报名
            if (ObjectUtil.isNotEmpty(registeredUserIds)) {
                String[] registeredUserIdArray = registeredUserIds.split(",");
                for (String userId : registeredUserIdArray) {
                    if (userId.trim().equals(String.valueOf(loginUserId))) {
                        bean.setUserIsRegistered(1); // 已报名
                        break;
                    }
                }
            }
            // 判断用户是否已咨询
            if (ObjectUtil.isNotEmpty(consultingUserIds)) {
                String[] consultingUserIdArray = consultingUserIds.split(",");
                for (String userId : consultingUserIdArray) {
                    if (userId.trim().equals(String.valueOf(loginUserId))) {
                        bean.setUserIsConsulting(1); // 已咨询
                        break;
                    }
                }
            }
            // 判断用户是否已报名(全部)
            if (ObjectUtil.isNotEmpty(isSignUpIds)) {
                String[] registeredUserIdArray = isSignUpIds.split(",");
                for (String userId : registeredUserIdArray) {
                    if (userId.trim().equals(String.valueOf(loginUserId))) {
                        bean.setUserIsSignUpIds(1); // 已报名
                        break;
                    }
                }
            }
        }
        return success(bean);
    }

    @PostMapping("/getAppPlatformInformationPage")
    @Operation(summary = "获得app平台信息列表")
    public CommonResult<PageResult<PlatformInformationRespVO>> getAppPlatformInformationPage(@Valid @RequestBody AppPlatformInformationPageReqVO pageReqVO) {
        PageResult<PlatformInformationDO> pageResult = platformInformationService.getAppPlatformInformationPage(pageReqVO);
        Long loginUserId = getLoginUserId();
        PageResult<PlatformInformationRespVO> bean = BeanUtils.toBean(pageResult, PlatformInformationRespVO.class);
        for (PlatformInformationRespVO platformInformationRespVO : bean.getList()) {
            if (ObjectUtil.isNotEmpty(platformInformationRespVO)){
                String consultingUserIds = platformInformationRespVO.getConsultingUserIds();
                // 判断用户是否咨询
                boolean isConsulting = false;
                if (consultingUserIds != null && !consultingUserIds.isEmpty()) {
                    isConsulting = Arrays.stream(consultingUserIds.split(","))
                            .map(String::trim)
                            .anyMatch(ids -> ids.equals(loginUserId.toString()));
                    platformInformationRespVO.setUserIsConsulting(isConsulting ? 1 : 0);
                }
                // 判断用户是否已报名
                String registeredUserIds = platformInformationRespVO.getRegisteredUserIds();
                boolean isCollected = false;
                if (registeredUserIds != null && !registeredUserIds.isEmpty()) {
                    isCollected = Arrays.stream(registeredUserIds.split(","))
                            .map(String::trim)
                            .anyMatch(ids -> ids.equals(loginUserId.toString()));
                            platformInformationRespVO.setUserIsRegistered(isCollected ? 1 : 0);
                }
            }
        }
        return success(bean);
    }
    @GetMapping("/getAppSpecialMeeting")
    @Operation(summary = "获得app专场会议管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PermitAll
    public CommonResult<SpecialMeetingRespVO> getAppSpecialMeeting(@RequestParam("id") Long id) {
        Long loginUserId = getLoginUserId();
        SpecialMeetingDO specialMeeting = specialMeetingService.getAppSpecialMeeting(id);
        SpecialMeetingRespVO respVO = BeanUtils.toBean(specialMeeting, SpecialMeetingRespVO.class);
        // 根据开始时间和结束时间设置会议状态
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(respVO.getStartTime())) {
            // 当前时间在开始时间之前，会议未开始
            respVO.setActiveState(0);
        } else if (now.isAfter(respVO.getEndTime())) {
            // 当前时间在结束时间之后，会议已结束
            respVO.setActiveState(2);
        } else {
            // 当前时间在开始时间和结束时间之间，会议进行中
            respVO.setActiveState(1);
        }
        String userCollectIds = specialMeeting.getUserCollectIds();
        //判断是否存在当前用户收藏，存在则返回数据

        // 使用Stream的检查方式
        boolean isCollected = false;
        if (userCollectIds != null && !userCollectIds.isEmpty()) {
            isCollected = Arrays.stream(userCollectIds.split(","))
                    .map(String::trim)
                    .anyMatch(ids -> ids.equals(loginUserId.toString()));
        }
        respVO.setIsCollect(isCollected ? 1 : 0);


        //返回报名状态  报名详情有数据的话就返回已报名
        if (ObjectUtil.isNotEmpty(loginUserId)) {
            ConferenceRegistrationInformationDO conferenceRegistrationInformationDO = conferenceRegistrationInformationMapper.selectOne(
                    new LambdaQueryWrapper<ConferenceRegistrationInformationDO>()
                            .eq(ConferenceRegistrationInformationDO::getMeetingId, id)
                            .eq(ConferenceRegistrationInformationDO::getUserId, loginUserId)
                            .eq(ConferenceRegistrationInformationDO::getPayStatus, 1)
            );
            if (ObjectUtil.isNotEmpty(conferenceRegistrationInformationDO)){
                respVO.setIsEnroll(1);
                respVO.setInformationId(conferenceRegistrationInformationDO.getId());
            }else {
                respVO.setIsEnroll(0);
            }
        }

        return success(respVO);
    }
    @PostMapping("/getAppSpecialMeetingPage")
    @Operation(summary = "获得app专场会议管理分页")
    @PermitAll
    public CommonResult<PageResult<SpecialMeetingRespVO>> getAppSpecialMeetingPage(@Valid @RequestBody AppSpecialMeetingPageReqVO pageReqVO) {
        PageResult<SpecialMeetingDO> pageResult = specialMeetingService.getAppSpecialMeetingPage(pageReqVO);
        PageResult<SpecialMeetingRespVO> bean = BeanUtils.toBean(pageResult, SpecialMeetingRespVO.class);
        bean.getList().forEach(item -> {
            // 根据开始时间和结束时间设置会议状态
            LocalDateTime now = LocalDateTime.now();
            if (now.isBefore(item.getStartTime())) {
                // 当前时间在开始时间之前，会议未开始
                item.setActiveState(0);
            } else if (now.isAfter(item.getEndTime())) {
                // 当前时间在结束时间之后，会议已结束
                item.setActiveState(2);
            } else {
                // 当前时间在开始时间和结束时间之间，会议进行中
                item.setActiveState(1);
            }
        });
        return success(bean);
    }
    @GetMapping("/getThirdPartyInformation")
    @Operation(summary = "获得第三方信息管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PermitAll
    public CommonResult<ThirdPartyInformationRespVO> getThirdPartyInformation(@RequestParam("id") Long id) {
        Long loginUserId = getLoginUserId();
        ThirdPartyInformationDO thirdPartyInformation = thirdPartyInformationService.getAppThirdPartyInformation(id);
        ThirdPartyInformationRespVO bean = BeanUtils.toBean(thirdPartyInformation, ThirdPartyInformationRespVO.class);
        String userCollectIds = thirdPartyInformation.getUserCollectIds();
        //判断是否存在当前用户收藏，存在则返回数据
        // 使用Stream的检查方式
        boolean isCollected = false;
        if (userCollectIds != null && !userCollectIds.isEmpty()) {
            isCollected = Arrays.stream(userCollectIds.split(","))
                    .map(String::trim)
                    .anyMatch(ids -> ids.equals(loginUserId.toString()));
        }
        bean.setIsCollect(isCollected ? 1 : 0);

        return success(bean);
    }

    @PostMapping("/getThirdPartyInformationPage")
    @Operation(summary = "获得第三方信息管理分页")
    public CommonResult<PageResult<ThirdPartyInformationRespVO>> getThirdPartyInformationPage(@Valid @RequestBody AppThirdPartyInformationPageReqVO pageReqVO) {
        PageResult<ThirdPartyInformationDO> pageResult = thirdPartyInformationService.getAppThirdPartyInformationPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ThirdPartyInformationRespVO.class));
    }

    @GetMapping("/getMarketInformation")
    @Operation(summary = "获得App市场资讯")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PermitAll
    public CommonResult<MarketInformationRespVO> getMarketInformation(@RequestParam("id") Integer id) {
        MarketInformationDO marketInformation = marketInformationService.getAppMarketInformation(id);
        return success(BeanUtils.toBean(marketInformation, MarketInformationRespVO.class));
    }

    @GetMapping("/getMarketInformationPage")
    @Operation(summary = "获得App市场资讯分页")
    @PermitAll
    public CommonResult<PageResult<MarketInformationRespVO>> getMarketInformationPage(@Valid MarketInformationPageReqVO pageReqVO) {
        PageResult<MarketInformationDO> pageResult = marketInformationService.getAppMarketInformationPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, MarketInformationRespVO.class));
    }


    @GetMapping("/getAppCarouselImageList")
    @Operation(summary = "获得轮播图list")
    @PermitAll
//    @PreAuthorize("@ss.hasPermission('biz:carousel-image:query')")
    public CommonResult<List<CarouselImageRespVO>> getAppCarouselImageList(@Valid CarouselImagePageReqVO pageReqVO) {
        List<CarouselImageDO> pageResult = carouselImageService.getAppCarouselImageList(pageReqVO);
        return success(BeanUtils.toBean(pageResult, CarouselImageRespVO.class));
    }
    @GetMapping("/getColumnTypeList")
    @Operation(summary = "获得栏目list")
    @PermitAll
    public CommonResult<List<ColumnTypeRespVO>> getAppColumnTypeList(@Valid ColumnTypePageReqVO pageReqVO) {
        List<ColumnTypeDO> pageResult = columnTypeService.getAppColumnTypeList(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ColumnTypeRespVO.class));
    }

}